import React from 'react'
import { 
  makeObservable, 
  observable, 
  action,
} from 'mobx';
import { observer } from 'mobx-react-lite';
import { mobxStore } from '../../store/mobxStore';
import { Button } from 'antd';
/* 声明一个store */
const mobxStores = new mobxStore()

const MobxTest = observer((props) => {
  console.group('<--- mobxTest --->')
  console.log('mobxTest props', props);
  console.groupEnd()
  return(
    <div>{'mobxTest===> '}{props.mobx.count}</div>
  )
})

/* 修改无效果，需要调用装饰器 函数组件observer() 类组件@observer */
// @observer
function FirstMobx(props) {
  console.log('props', props);
  console.group('<---   FirstMbox   --->')

  /* decorator 是怎么运行的 */
  function log(target) {
    // target 代表修饰的类
    // console.log('target', target.prototype);
    const desc = Object.getOwnPropertyDescriptors(target.prototype)
    // console.log('desc', desc);
    for (const key of Object.keys(desc)) {
      if( key === 'constructor' ) {
        continue;
      }
      const func = desc[key].value
      if('function' === typeof func) {
        Object.defineProperty(target.prototype, key, {
          value(...args) {
            console.log('before ' + key);
            const ret = func.apply(this, args)
            console.log('after ' + key);
            return ret
          }
        })
      }
    }
  }
  /* 只读属性 */
  function readonly(target, kye, descriptor) {
    descriptor.writable = false
  }
  /* log用来的修饰 Numberic */
  @log
  class Numberic {
    title = ''
    constructor(title) {
      /* 自动监听数据变化 */
      makeObservable(this, {
        title: observable,
        toggle: action
      })
      this.title = title
    }

    id = Math.random();
    name = 'Numberic';
    @readonly PI = 3.1415926;
    add(...nums) {
      return nums.reduce((p, n) => (p + n), 0)
    }
    toggle() {
      this.id *=200
      console.log('<<<--- toggle Mobx 监听 --->>>', this.id);
    }
  }
  console.log('Mobx Numberic', new Numberic());
  console.log('PI', new Numberic().PI );
  console.log('add', new Numberic().add(1, 2, 3, 4));
  console.log('title', new Numberic().title = 'Numberic title' );
  console.log('toggle',  );
  new Numberic().toggle()

  const arr = observable(['a', 'b', 'c'])
  console.log('mobx arr', arr);


  /* 引入的公共厂库 */
  console.log('mobxStore 公共厂库', mobxStores );



  console.groupEnd()
  const numberics = new Numberic()
  return (
    <React.StrictMode>
      <MobxTest mobx={mobxStores} />

      <h3>{'修改本地 mobxStore 中的数据   ---   '}{numberics.id}</h3>
      <Button onClick={() => {
        numberics.toggle()
      }}>修改本地数据</Button>

      <h3>{'点击修改 mobxStore 中的数据 ---  '}{mobxStores.count}</h3>
      <Button type="primary"
        onClick={()=>{
          /* 修改无效果，需要调用装饰器 @observer */
          mobxStores.increment()
        }}
      >mobxStore 修改</Button>
    </React.StrictMode>
  )
}

export default observer(FirstMobx)